<template>
	<div>
		<Title />
		<div ref="chartContainer" style="width: 100%; height: 900px;"></div>
	</div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { useScreenStore } from '@/store';
import Title from '../Title.vue';
import * as echarts from 'echarts';
import chengduJson from '@/assets/data/cd.json';
import piduJson from '@/assets/data/pidu.json';
import cdjcImage from '@/assets/images/screen/JC.png';

// 注册地图数据
echarts.registerMap('cd', chengduJson as any);
echarts.registerMap('pidu', piduJson as any);

const store = useScreenStore();
const currentMap = ref('cd');

const getOption = (mapName, theme) => {
	if (mapName === 'cdjc') {
		return {
			graphic: [
				{
					type: 'image',
					id: 'cdjc',
					left: 'center', // 水平方向居中
					top: '100px', // 尝试更小的值，甚至负值
					z: 10,
					style: {
						image: cdjcImage,
						width: 800,
						height: 700,
					},
				},
			],
			geo: null, // 清空geo配置
			series: [], // 清空地图系列数据
		};
	}
	return {
		geo: {
			type: 'map',
			map: mapName,
			top: '5%',
			bottom: '5%',
			itemStyle: {
				areaColor: theme === 'dark' ? '#2E3A59' : '#000',
				borderColor: theme === 'dark' ? '#FF6347' : '#2E72BF',
				borderWidth: 5,
				shadowColor: 'rgba(0, 0, 0, 0.5)',
				shadowBlur: 5,
			},
			emphasis: {
				itemStyle: {
					areaColor: theme === 'dark' ? '#4B6A88' : '#FFD700',
					borderColor: '#FFF',
					borderWidth: 9,
				},
			},
		},
		series: [
			{
				type: 'map',
				map: mapName,
				emphasis: {
					itemStyle: {
						areaColor: theme === 'dark' ? '#FF6347' : '#FFD700',
					},
				},
				select: {
					itemStyle: {
						areaColor: theme === 'dark' ? '#FF6347' : '#FFD700',
					},
					label: {
						show: true,
						color: theme === 'dark' ? '#FFFFFF' : '#000000',
					},
				},
				regions: [
					{
						name: '郫都区',
						selected: mapName === 'cd',
					},
				],
			},
		],
	};
};

const option = ref(getOption(currentMap.value, store.theme));

// 打印调试信息
console.log(option.value);

watch(() => store.theme, (newTheme) => {
	option.value = getOption(currentMap.value, newTheme);
	if (chartInstance.value) {
		chartInstance.value?.setOption(option.value, true); // 传递第二个参数以合并配置
	}
});

const handleClick = (params) => {
	if (params.name === '郫都区') {
		if (currentMap.value === 'cd') {
			// 切换到 pidu 并高亮
			currentMap.value = 'pidu';
		} else if (currentMap.value === 'pidu') {
			// 切换到 cdjc 显示图片
			currentMap.value = 'cdjc';
		}
		option.value = getOption(currentMap.value, store.theme);
		if (chartInstance.value) {
			chartInstance.value?.setOption(option.value, true); // 传递第二个参数以合并配置
		}
	}
};

const chartInstance = ref<echarts.ECharts | null>(null);
const chartContainer = ref<HTMLElement | null>(null);

onMounted(() => {
	if (chartContainer.value) {
		chartInstance.value = echarts.init(chartContainer.value);
		chartInstance.value?.setOption(option.value, true); // 传递第二个参数以合并配置
		chartInstance.value?.on('click', handleClick);
	}
});
</script>
